(function () {

  'use strict';

  angular
  .module('app')
  .controller('CommentController', CommentController);

  CommentController.$inject = ['$scope', '$http', '$window', '$timeout', '$location', '$state', '$stateParams', 'API'];

  function CommentController($scope, $http, $window, $timeout, $location, $state, $stateParams, API) {

      var PER_PAGE = 10;
      var CURRENT_PAGE = 1;
      var TOTAL_PAGE = 0;
      var goodsID = $stateParams.goods_id;

      $scope.isEmpty = false;
      $scope.isLoaded = false;
      $scope.isLoading = false;
      $scope.isLastPage = false;
      $scope.level = 0;
      $scope.comments = null;

      $scope.touchTab = function(level) {
          $scope.level = level;
          _reload();
      };

      $scope.loadMore = function() {
          if ( $scope.isLoading )
              return;
          if ( $scope.isLastPage )
              return;

          if (CURRENT_PAGE < TOTAL_PAGE) {
              _fetch( CURRENT_PAGE + 1, PER_PAGE );
          } else {
              _fetch( 1, PER_PAGE );
          }
      };

      function _fetch(page, perPage) {
          $scope.isLoading = true;
          API.review.goodsComment({
              relation_id:goodsID,
              level:$scope.level,
              page:page,
              per_page:perPage
          }).then(function(res){
              $scope.comments = $scope.comments ? $scope.comments.concat(res.rows) : res.rows;
              $scope.isEmpty = res.total ? false : true;
              $scope.isLoaded = true;
              $scope.isLoading = false;
              $scope.isLastPage = res.current_page==res.total_page ? !$scope.isEmpty : false;
              CURRENT_PAGE = res.current_page;
              TOTAL_PAGE = res.total_page;
          });
      }

      function _reload() {
          if ( $scope.isLoading )
              return;

          $scope.comments = null;
          $scope.isEmpty = false;
          $scope.isLoaded = false;

          _fetch( 1, PER_PAGE );
      }

      _reload();
  }

})();
